package com.ruoyi.phoneController;

import java.util.Map;

import com.ruoyi.domain.MobileLoginUser;
import com.ruoyi.service.MobileTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.CrossOrigin;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.domain.MobileUser;
import com.ruoyi.service.IMobileUserService;

/**
 * 手机端用户Controller
 * 
 * @author ruoyi
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/mobile/user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class MobileUserController extends BaseController
{
    @Autowired
    private IMobileUserService mobileUserService;

    @Autowired
    private MobileTokenService mobileTokenService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody MobileUserLoginRequest loginRequest)
    {
        logger.info("接收到登录请求，参数：{}", loginRequest != null ? "phone=" + loginRequest.getPhone() : "loginRequest为null");
        
        // 参数校验
        if (loginRequest == null || StringUtils.isEmpty(loginRequest.getPhone()) || StringUtils.isEmpty(loginRequest.getPassword()))
        {
            return error("手机号和密码不能为空");
        }

        // 手机号格式校验
        if (!isValidPhone(loginRequest.getPhone()))
        {
            return error("手机号格式不正确");
        }

        try
        {
            // 执行登录
            MobileUser user = mobileUserService.login(loginRequest.getPhone(), loginRequest.getPassword());
            
            if (user == null)
            {
                return error("手机号或密码错误");
            }

            // 创建登录用户对象
            MobileLoginUser loginUser = new MobileLoginUser(user);

            // 生成JWT令牌
            Map<String, Object> tokenInfo = mobileTokenService.createToken(loginUser);
            
            // 添加调试日志
            logger.info("登录成功，用户信息: {}", user);
            logger.info("生成的token信息: {}", tokenInfo);
            logger.info("返回的AjaxResult: {}", success(tokenInfo));

            //"登录成功",
            return success( tokenInfo);
        }
        catch (Exception e)
        {
            logger.error("用户登录失败", e);
            return error("登录失败，请稍后重试");
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public AjaxResult getUserInfo()
    {
        try
        {
            MobileLoginUser loginUser = mobileTokenService.getLoginUser();
            if (loginUser == null || loginUser.getUser() == null)
            {
                return error("用户未登录或登录已过期");
            }

            //"获取用户信息成功",
            return success(loginUser.getUser());
        }
        catch (Exception e)
        {
            logger.error("获取用户信息失败", e);
            return error("获取用户信息失败");
        }
    }

    /**
     * 用户退出登录
     */
    @PostMapping("/logout")
    public AjaxResult logout()
    {
        try
        {
            MobileLoginUser loginUser = mobileTokenService.getLoginUser();
            if (loginUser != null && StringUtils.isNotEmpty(loginUser.getToken()))
            {
                mobileTokenService.delLoginUser(loginUser.getToken());
            }
            return success("退出成功");
        }
        catch (Exception e)
        {
            logger.error("用户退出登录失败", e);
            return error("退出失败");
        }
    }

    /**
     * 刷新令牌
     */
    @PostMapping("/refresh")
    public AjaxResult refreshToken()
    {
        try
        {
            MobileLoginUser loginUser = mobileTokenService.getLoginUser();
            if (loginUser == null)
            {
                return error("用户未登录或登录已过期");
            }

            mobileTokenService.refreshToken(loginUser);
            Map<String, Object> tokenInfo = mobileTokenService.createToken(loginUser);

            //"令牌刷新成功",
            return success( tokenInfo);
        }
        catch (Exception e)
        {
            logger.error("刷新令牌失败", e);
            return error("刷新令牌失败");
        }
    }

    /**
     * 根据用户ID查询用户信息
     */
    @GetMapping("/{id}")
    public AjaxResult getUserById(@PathVariable Integer id)
    {
        if (id == null || id <= 0)
        {
            return error("用户ID不能为空");
        }

        try
        {
            MobileUser user = mobileUserService.selectMobileUserById(id);
            if (user == null)
            {
                return error("用户不存在");
            }

            // 清空敏感信息
            user.setPassword(null);

            //"查询成功",
            return success( user);
        }
        catch (Exception e)
        {
            logger.error("查询用户信息失败", e);
            return error("查询用户信息失败");
        }
    }

    /**
     * 校验手机号格式
     */
    private boolean isValidPhone(String phone)
    {
        if (StringUtils.isEmpty(phone))
        {
            return false;
        }
        
        // 简单的手机号格式校验，以1开头的11位数字
        String phonePattern = "^1[3-9]\\d{9}$";
        return phone.matches(phonePattern);
    }

    /**
     * 登录请求对象
     */
    public static class MobileUserLoginRequest
    {
        private String phone;
        private String password;

        public String getPhone()
        {
            return phone;
        }

        public void setPhone(String phone)
        {
            this.phone = phone;
        }

        public String getPassword()
        {
            return password;
        }

        public void setPassword(String password)
        {
            this.password = password;
        }
    }

    /**
     * 验证支付密码
     */
    @PostMapping("/verifyPayPassword")
    public AjaxResult verifyPayPassword(@RequestBody PayPasswordRequest request)
    {
        if (request == null || StringUtils.isEmpty(request.getPayPassword()))
        {
            return error("支付密码不能为空");
        }

        try
        {
            // 获取当前登录用户
            MobileLoginUser loginUser = mobileTokenService.getLoginUser();
            if (loginUser == null || loginUser.getUser() == null)
            {
                return error("用户未登录或登录已过期");
            }

            Integer userId = loginUser.getUser().getId();
            
            // 验证支付密码
            boolean isValid = mobileUserService.verifyPayPassword(userId, request.getPayPassword());
            
            if (isValid)
            {
                return success("支付密码验证成功");
            }
            else
            {
                return error("支付密码错误");
            }
        }
        catch (Exception e)
        {
            logger.error("验证支付密码失败", e);
            return error("验证支付密码失败");
        }
    }

    /**
     * 修改支付密码
     */
    @PostMapping("/updatePayPassword")
    public AjaxResult updatePayPassword(@RequestBody UpdatePayPasswordRequest request)
    {
        if (request == null || StringUtils.isEmpty(request.getNewPayPassword()))
        {
            return error("新支付密码不能为空");
        }

        try
        {
            // 获取当前登录用户
            MobileLoginUser loginUser = mobileTokenService.getLoginUser();
            if (loginUser == null || loginUser.getUser() == null)
            {
                return error("用户未登录或登录已过期");
            }

            Integer userId = loginUser.getUser().getId();
            
            // 如果提供了旧密码，先验证旧密码
            if (!StringUtils.isEmpty(request.getOldPayPassword()))
            {
                boolean isOldPasswordValid = mobileUserService.verifyPayPassword(userId, request.getOldPayPassword());
                if (!isOldPasswordValid)
                {
                    return error("原支付密码错误");
                }
            }
            
            // 更新支付密码
            int result = mobileUserService.updatePayPassword(userId, request.getNewPayPassword());
            
            if (result > 0)
            {
                return success("支付密码修改成功");
            }
            else
            {
                return error("支付密码修改失败");
            }
        }
        catch (Exception e)
        {
            logger.error("修改支付密码失败", e);
            return error("修改支付密码失败");
        }
    }

    /**
     * 支付密码验证请求对象
     */
    public static class PayPasswordRequest
    {
        private String payPassword;

        public String getPayPassword()
        {
            return payPassword;
        }

        public void setPayPassword(String payPassword)
        {
            this.payPassword = payPassword;
        }
    }

    /**
     * 修改支付密码请求对象
     */
    public static class UpdatePayPasswordRequest
    {
        private String oldPayPassword;
        private String newPayPassword;

        public String getOldPayPassword()
        {
            return oldPayPassword;
        }

        public void setOldPayPassword(String oldPayPassword)
        {
            this.oldPayPassword = oldPayPassword;
        }

        public String getNewPayPassword()
        {
            return newPayPassword;
        }

        public void setNewPayPassword(String newPayPassword)
        {
            this.newPayPassword = newPayPassword;
        }
    }
}
